import fetch from '@/utils/network/fetch'

const gettrainTask = (data, objc) => {
    fetch('/api/training', {
        ...objc,
        method: 'post',
        data
    })
}

const removeonetrain = (lIds, objc) => {
    lIds &&
        fetch('/api/training/deletion', {
            ...objc,
            method: 'post',
            data: { lIds }
        })
}

const addTrain = (data, objc) => {
    data &&
        fetch('/api/training', {
            ...objc,
            method: 'put',
            data
        })
}

const editTrain = (data, objc) => {
    console.log('---====...objc,')
    console.log(data)
    console.log('---====...objc,')
    data &&
        fetch(`/api/training/${data.id}`, {
            loading: true,
            ...objc,
            data,
            method: 'put'
        })
}

const getTrainDetail = (data, objc) => {
    data &&
        fetch(`/api/training/${data.id}`, {
            loading: true,
            data,
            method: 'get',
            ...objc
        })
}

const addLearnRelation = (data, objc) => {
    data &&
        fetch(`/api/training/${data.id}/learning_relation`, {
            loading: true,
            ...objc,
            method: 'put',
            data
        })
}

const addTrineeRelation = (data, objc) => {
    data &&
        fetch(`/api/training/${data.id}/trainee_relation`, {
            loading: true,
            ...objc,
            method: 'put',
            data
        })
}

const getTrainingsByTrainee = (data, objc) => {
    data &&
        fetch('/api/training', {
            ...objc,
            method: 'post',
            data: { ...data, ...{ strategy: 'business' } }
        })
}

const getBusinessTemplatesFromTraining = training => {
    let businesses = []
    let businessMap = {}
    if (training && training.learningTasks) {
        for (const learningTask of training.learningTasks) {
            if (learningTask.businessTemplates) {
                for (const businessTemplate of learningTask.businessTemplates) {
                    if (!businessMap[businessTemplate.id] && businessTemplate.enabled) {
                        businessMap[businessTemplate.id] = true
                        businesses.push(businessTemplate)
                    }
                }
            }
        }
    }
    return businesses
}

export default {
    gettrainTask,
    getTrainDetail,
    removeonetrain,
    addLearnRelation,
    addTrineeRelation,
    addTrain,
    editTrain,
    getTrainingsByTrainee,
    getBusinessTemplatesFromTraining
}
